package com.cqu.hospitalsystem.service.impl;

import com.cqu.hospitalsystem.service.AdminService;
import com.cqu.hospitalsystem.utils.result.DataResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class AdminServiceImpl implements AdminService {

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${spring.datasource.url}")
    private String url;

    private final String mysqldumpPath = "D:\\mysql\\bin\\mysqldump.exe"; // mysqldump的完整路径

    private final String backupUrl = "D:\\0\\winterProject\\file\\DB";

    private final String databaseName = "hospital";

    @Override
    public DataResult backupDB() {
        DataResult dataResult = DataResult.err();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        String dateString = dateFormat.format(new Date());
        String backupFileName = "backup-" + dateString + ".sql";
        String backupFilePath = backupUrl + File.separator + backupFileName; // 使用File.separator确保路径正确

        // 确保备份目录存在
        File backupDir = new File(backupUrl);
        if (!backupDir.exists()) {
            backupDir.mkdirs();
        }

        // 构建备份命令
        String command = "cmd.exe /c \"mysqldump -u " + username + " -p" + password + " " + databaseName + " > " + backupFilePath + "\"";

        try {
            Process process = Runtime.getRuntime().exec(command);
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                System.out.println("Database backup successful, file saved at: " + backupFilePath);
                dataResult = DataResult.succ();
            } else {
                System.out.println("Database backup failed with exit code: " + exitCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataResult;
    }
}